package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import com.heima.model.user.dtos.AppLoginDto;
import com.heima.model.user.dtos.UserFlag;
import com.heima.model.user.dtos.UserInfoDto;
import com.heima.user.entity.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-02-01
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 修改ap_user的身份、状态
     * @param userId
     */
    @Override
    public void authSucc(Integer userId) {
        ApUser apUser = new ApUser();
        apUser.setId(userId);
        apUser.setFlag(UserFlag.WAIT.getCode());
        apUser.setIsIdentityAuthentication(true);
        this.updateById(apUser);
    }
    private final static Integer TOKEN_TIME = 120;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public ResponseResult login(AppLoginDto dto) {
        //条件查询
        LambdaQueryWrapper<ApUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ApUser::getPhone,dto.getPhone());
        ApUser adUser = this.getOne(lqw);
        //判断adUser是否存在
        if (adUser == null){
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        String passwordDB = adUser.getPassword();
        String password = dto.getPassword();
        boolean b = encoder.matches(password, passwordDB);
        if (!b){
            //如果密码不对  抛出异常
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //设置token
        Map<String,Object> map = new HashMap<>();
        String token = JwtUtils.generateTokenExpireInMinutes(adUser.getId(), TOKEN_TIME);
        map.put("token",token);
        UserInfoDto userInfoDto = new UserInfoDto();
        BeanUtils.copyProperties(adUser, userInfoDto);
        map.put("user",userInfoDto);
        return ResponseResult.ok(map);

    }
}
